import { onHide } from '@dcloudio/uni-app';
<!--
 * @Description:
 * @Date: 2024-05-14 09:00:16
 * @LastEditTime: 2024-09-14 10:10:30
-->
<route lang="json5" type="login">
{
  style: {
    navigationBarTitleText: '电子送达',
    navigationBarTextStyle: 'white', //标题栏字体颜色
    navigationBarBackgroundColor: '#0063AF', //标题栏背景色(纯色)
  },
}
</route>
<template>
  <view class="w-screen h-screen flex flex-col p-10rpx box-border bg-#fff">
    <wd-form ref="form" class="w-100%" :model="model" :rules="rules">
      <wd-cell-group border>
        <wd-input
          label="送达文号"
          label-width="100px"
          prop="number"
          clearable
          v-model="model.number"
          placeholder="请输入送达文号"
          :rules="[{ required: true, message: '请填写送达文号' }]"
        />
        <wd-picker
          label="文件类型"
          placeholder="请选择文件类型"
          label-width="100px"
          prop="fileType"
          v-model="model.fileType"
          :columns="promotionlist"
          :rules="[{ required: true, message: '请选择文件类型' }]"
        />
        <wd-input
          label="被送达人姓名"
          label-width="100px"
          prop="acceptName"
          clearable
          v-model="model.acceptName"
          placeholder="请输入被送达人姓名"
          :rules="[{ required: true, message: '请填写被送达人姓名' }]"
        />
        <wd-input
          label="被送达人身份证号"
          label-width="100px"
          prop="acceptCard"
          type="idcard"
          clearable
          v-model="model.acceptCard"
          placeholder="请输入被送达人身份证号"
        />
        <wd-input
          label="被送达人联系式"
          label-width="100px"
          prop="acceptPhone"
          type="idcard"
          clearable
          v-model="model.acceptPhone"
          placeholder="请输入被送达人联系式"
        />
        <wd-input
          label="案件编号"
          label-width="100px"
          prop="caseNumber"
          clearable
          v-model="model.caseNumber"
          placeholder="请输入案件编号"
          :rules="[{ required: true, message: '请填写案件编号' }]"
        />
        <wd-input
          label="案件名称"
          label-width="100px"
          prop="caseName"
          v-model="model.caseName"
          placeholder="请输入案件名称"
          :rules="[{ required: true, message: '请填写案件名称' }]"
        />
        <wd-cell title="检察官签名" title-width="180rpx" prop="proSignatureUrl">
          <view class="flex flex-col gap-20rpx">
            <wd-button size="small" icon="backtop" @click="handleSignature">上传签名照片</wd-button>
            <wd-img
              v-if="model.proSignatureUrl"
              :width="200"
              :height="100"
              :src="baseurl + model.proSignatureUrl"
              :enable-preview="true"
            />
          </view>
        </wd-cell>
        <wd-cell title="相关附件" title-width="180rpx" prop="fileList">
          <view class="flex flex-col gap-20rpx">
            <wd-button size="small" icon="backtop" @click="handleFile">选择文件</wd-button>
            <view>
              <view v-for="(item, index) in model.fileList" :key="index">
                <text class="mr-30rpx my-20rpx">{{ item.name }}</text>
                <wd-icon
                  name="delete"
                  size="18px"
                  color="#ec2828"
                  @click="handleDelete(index)"
                ></wd-icon>
              </view>
            </view>
          </view>
        </wd-cell>
        <wd-textarea
          label="备注"
          label-width="100px"
          type="textarea"
          v-model="model.proRemark"
          :maxlength="300"
          show-word-limit
          placeholder="请输入备注"
          clearable
          prop="proRemark"
          :rules="[{ required: false, message: '请输入备注' }]"
        />
      </wd-cell-group>

      <view class="footer">
        <wd-button class="bg-#0A4484" type="primary" size="large" @click="handleSubmit" block>
          提交
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store'
import { useToast } from 'wot-design-uni'
import { electronicAPI } from '@/service/index/foo'
const toast = useToast()
const baseurl = import.meta.env.VITE_SERVER_BASEURL
const form = ref()
const promotionlist = ref<any[]>([
  {
    value: '1',
    label: '起诉书',
  },
  {
    value: '2',
    label: '抗诉书',
  },
  {
    value: '3',
    label: '补充侦查决定书',
  },
  {
    value: '4',
    label: '证据清单',
  },
  {
    value: '5',
    label: '传票',
  },
  {
    value: '6',
    label: '量刑建议书',
  },
  {
    value: '7',
    label: '申诉复查决定书',
  },
  {
    value: '8',
    label: '检察建议书',
  },
  {
    value: '9',
    label: '其他',
  },
])
const baseUrl = import.meta.env.VITE_SERVER_BASEURL
const userStore = useUserStore()
const model = reactive<{
  number: string
  fileType: string
  acceptName: string
  acceptCard: string
  acceptPhone: string
  caseNumber: string
  caseName: string
  proSignatureUrl: string
  files: string[]
  fileList: string[]
  proRemark: string
  status: number
  businessType: string
}>({
  number: '',
  fileType: '',
  acceptName: '',
  acceptCard: '',
  acceptPhone: '',
  caseNumber: '',
  caseName: '',
  files: [],
  fileList: [],
  proSignatureUrl: '',
  proRemark: '',
  status: 1,
  businessType: 'Dian',
})
onShow(() => {
  const pages = getCurrentPages()
  const currPage = pages[pages.length - 1] // 当前页的实例
  if (currPage.$vm.url) model.proSignatureUrl = currPage.$vm.url
})
const rules = {
  fileList: [
    {
      required: true,
      message: '请选择上传材料',
      validator: (value) => {
        if (Array.isArray(value) && value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject('请选择上传材料')
        }
      },
    },
  ],
  proSignatureUrl: [
    {
      required: true,
      message: '请上传检察官签名',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请上传检察官签名'))
        }
      },
    },
  ],
  acceptCard: [
    {
      required: false,
      message: '请输入正确的身份证号',
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\d|X|x]$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入身份证号')
        }
      },
    },
  ],
  acceptPhone: [
    {
      required: true,
      message: '请输入正确的手机号',
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入手机号')
        }
      },
    },
  ],
}
const handleSignature = () => {
  uni.navigateTo({ url: '/pages/ElectronicDelivery/Draw' })
}
function handleFile() {
  wx.chooseMessageFile({
    count: 1, // 限制选择的文件数量
    type: 'file', // 非图片和视频的文件,不选默认为all
    extension: ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'], // 此处限制文件类型
    // extension: ['xls', 'xlsx'], //此处限制文件类型
    success(res) {
      const tempFilePaths = res.tempFiles
      toast.loading({
        msg: '上传中...',
      })
      // 下面是返回后需要调接口的操作
      const uploadTask = uni.uploadFile({
        url: '/app-api/infra/file/upload-id',
        filePath: tempFilePaths[0].path,
        method: 'POST',
        name: 'file',
        formData: {
          name: tempFilePaths[0].name,
        },
        success: (uploadFileRes) => {
          // 接口返回的数据

          model.fileList.push(tempFilePaths[0])
          const { data } = JSON.parse(uploadFileRes.data)
          model.files.push(data)
          toast.close()
        },
        fail: () => {
          toast.close()
        },
      })
      uploadTask.onProgressUpdate((res) => {
        toast.loading({
          msg: '上传中' + res.progress + '%',
        })
        if (res.progress == 100) {
          toast.close()
        }
      })
    },
  })
}
function handleDelete(index) {
  model.fileList.splice(index, 1)
  model.files.splice(index, 1)
}
function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      console.log(valid)
      if (valid) {
        try {
          electronicAPI({
            ...model,
            fileList: undefined,
            files: [...model.files],
          }).then((res) => {
            if (res.code !== 0) {
              toast.error({
                msg: res.msg,
                duration: 0,
              })
              setTimeout(() => {
                toast.close()
              }, 1500)
            } else {
              toast.success({
                msg: '操作成功',
                duration: 0,
              })
              setTimeout(() => {
                uni.navigateBack()
                toast.close()
              }, 1500)
            }
          })
        } catch (error) {
          console.log(error)
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
</script>
<style lang="scss" scoped>
::v-deep .wd-form {
  width: 100%;
}

::v-deep .wd-cell__left {
  flex: none !important;
}

::v-deep .wd-cell__value {
  display: flex !important;
  justify-content: start !important;
}

::v-deep .wd-cell__value > .wd-button,
::v-deep .wd-cell__value > view > .wd-button {
  width: max-content !important;
  margin: 0 !important;
}

::v-deep .wd-picker__placeholder {
  color: #767575 !important;
}
</style>
